<?php

namespace core\lib;

/**
 * Class Route
 * @package core\lib
 */
class Route
{
    // 模块
    public $module;
    // 控制器
    public $ctrl;
    // 方法
    public $action;

    /**
     * 解析URL, 获取控制器，方法，参数
     * Route constructor.
     */
    public function __construct()
    {
        /**
         * 1.隐藏index.php
         * 2.获取URL, 参数部分
         * 3.返回对应控制器和方法
         */
        if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] != '/') {
            $path = $_SERVER['REQUEST_URI'];
            if (strpos($path, '/index.php') !== false) {
                $path = str_replace('/index.php', '', $path);
                $path = trim($path, '/');
                //p($path, strlen($path));
                if (strlen($path) == '0') {
                    $this->ctrl = Config::get('CTRL', 'route');
                    $this->action = Config::get('ACTION', 'route');
                    return;
                }
            }

            $urlArr = explode('?', trim($path, '/'));
            $pathArr = explode('/', trim($urlArr[0], '/'));
            //p($path, $pathArr, $urlArr[1]);
            if (count($pathArr) % 2 != 0) {
                //$pathArr[] = 'index';
            }
            if (count($pathArr) == 3) {
                $this->module = $pathArr[0];
                array_shift($pathArr);
            }
            //p($path, $pathArr, $urlArr[1]);

            if (isset($pathArr[0])) {
                $this->ctrl = $pathArr[0];
            }
            unset($pathArr[0]);

            if (isset($pathArr[1])) {
                $this->action = $pathArr[1];
            } else {
                $this->action = Config::get('ACTION', 'route');
            }
            unset($pathArr[1]);

            // 获取参数
            $count = count($pathArr) + 2;
            $i = 2;
            while ($i < $count) {
                if (isset($pathArr[$i + 1])) {
                    $_GET[$pathArr[$i]] = $pathArr[$i + 1];
                    $i += 2;
                }
            }

            if ($urlArr[1]) {
                $paramArr = explode('&', $urlArr[1]);
                foreach ($paramArr as $i => $val) {
                    $param = explode('=', $val);
                    $_GET[$param[0]] = $param[1];
                }
            }
        } else {
            $this->ctrl = Config::get('CTRL', 'route');
            $this->action = Config::get('ACTION', 'route');
        }
    }
}